package com.aramis.mydytt.ui.search

import androidx.lifecycle.MutableLiveData
import com.aramis.mydytt.ext.KV_HISTORY_KEY
import com.aramis.mydytt.ext.logE
import com.aramis.mydytt.ui.base.BaseViewModel
import com.aramis.mydytt.ui.bean.MovieItemBean
import com.aramis.mydytt.util.MMKVUtil
import io.reactivex.schedulers.Schedulers
import java.lang.StringBuilder

/**
 * Description: SearchResultViewModel
 * @author lizhidan
 * Created: 2021/5/25
 */
class SearchResultViewModel : BaseViewModel() {
    val searchLiveData = MutableLiveData<List<MovieItemBean>?>()

    fun search(key: String) {
        putSearchHistory(key)
        compositeDisposable.add(
            movieApi.search(key).subscribeOn(Schedulers.io()).subscribe({ wrapper ->
                logE("搜索成功：$wrapper")
                if (wrapper.dataNotNull() && wrapper.data!!.isNotEmpty()) {
                    searchLiveData.postValue(wrapper.data.map { it.toMovieItemBean() })
                } else {
                    searchLiveData.postValue(null)
                }
            }, {
                logE("搜索报错：" + it.message + it.javaClass.name)
                searchLiveData.postValue(null)
            })
        )
    }

    private fun putSearchHistory(key: String) {
        val history = MMKVUtil.getString(KV_HISTORY_KEY)
        if (history == null) {
            MMKVUtil.putString(KV_HISTORY_KEY, key)
        } else {
            if (history.contains(',')) {
                val historyList = history.split(',').filter { it.isNotBlank() }
                if (historyList.size < 10) {
                    MMKVUtil.putString(KV_HISTORY_KEY, "$key,$history")
                } else {
                    val stringBuilder = StringBuilder()
                    stringBuilder.append(key)
                    (0..8).forEach {
                        stringBuilder.append(",")
                        stringBuilder.append(historyList[it])
                    }
                    MMKVUtil.putString(KV_HISTORY_KEY, stringBuilder.toString())
                }
            } else {
                MMKVUtil.putString(KV_HISTORY_KEY, "$key,$history")
            }
        }
    }

    fun getSearchHistory(): List<String> {
        val history = MMKVUtil.getString(KV_HISTORY_KEY)
        if (history != null) {
            return if (history.contains(',')) {
                history.split(',').filter { it.isNotBlank() }
            } else {
                mutableListOf(history)
            }
        }
        return mutableListOf()
    }
}